{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第二周作业"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 作业1\n",
    "为了统计学生人数，可以给Student类增加一个类属性，每创建一个实例，该属性自动增加：  \n",
    "class Student(object):  \n",
    "count = 0  \n",
    "def __init__(self, name):  \n",
    "self.name = name  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建了1个学生实例\n",
      "创建了2个学生实例\n",
      "创建了3个学生实例\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "@Descripttion: \n",
    "@version: \n",
    "@Author: dkolli\n",
    "@Date: 2019-11-02 01:29:11\n",
    "@LastEditors: sueRimn\n",
    "@LastEditTime: 2019-11-02 01:49:34\n",
    "'''\n",
    "class Student(object):\n",
    "    count = 0  # Student类的属性\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "        # 每初始化一个实例对象，就毁掉用一次Student的add_num方法\n",
    "        self.add_num() \n",
    "        \n",
    "    def add_num(self):\n",
    "        # 计数增加1\n",
    "        Student.count += 1\n",
    "        \n",
    "\n",
    "xiaohong = Student('xiaohong')\n",
    "print('创建了%d个学生实例' % Student.count)\n",
    "\n",
    "xiaobai = Student('xiaobai')\n",
    "print('创建了%d个学生实例' % Student.count)\n",
    "\n",
    "xiaobai = Student('xiaobai')\n",
    "print('创建了%d个学生实例' % Student.count)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "***"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 作业2\n",
    "请设计一个装饰器，它可以作用于任何函数上，打印函数执行时间：\n",
    "import time\n",
    "def metric(fn):\n",
    "start_time = time.time()\n",
    "end_time = time.time()\n",
    "\n",
    "print('耗时：{:.4f}s'.format(end_time - start_time))\n",
    "return fn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "正常右上角写法的while思路\n",
      "9*9=81   9*8=72   9*7=63   9*6=54   9*5=45   9*4=36   9*3=27   9*2=18   9*1=9    \n",
      "         8*8=64   8*7=56   8*6=48   8*5=40   8*4=32   8*3=24   8*2=16   8*1=8    \n",
      "                  7*7=49   7*6=42   7*5=35   7*4=28   7*3=21   7*2=14   7*1=7    \n",
      "                           6*6=36   6*5=30   6*4=24   6*3=18   6*2=12   6*1=6    \n",
      "                                    5*5=25   5*4=20   5*3=15   5*2=10   5*1=5    \n",
      "                                             4*4=16   4*3=12   4*2=8    4*1=4    \n",
      "                                                      3*3=9    3*2=6    3*1=3    \n",
      "                                                               2*2=4    2*1=2    \n",
      "                                                                        1*1=1    \n",
      "耗时：0.00296760s\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "@Descripttion: \n",
    "@version: \n",
    "@Author: dkolli\n",
    "@Date: 2019-11-02 01:50:48\n",
    "@LastEditors: sueRimn\n",
    "@LastEditTime: 2019-11-02 12:57:10\n",
    "'''\n",
    "import time\n",
    "\n",
    "def metric(fn):\n",
    "    # 对程序进行封装\n",
    "    def wrapper():\n",
    "        # 在程序执行之前记录一次时间\n",
    "        start_time = time.time()\n",
    "        # 需要执行一次程序  \n",
    "        fn()\n",
    "        # 在程序执行之后记录一次时间\n",
    "        end_time = time.time()\n",
    "        # 两次时间相见，得到的差就是程序执行时间\n",
    "        print('耗时：{:.8f}s'.format(end_time - start_time))    \n",
    "    return wrapper\n",
    "\n",
    "@metric\n",
    "def multiplication_table():\n",
    "    print('正常右上角写法的while思路')\n",
    "    row = 9\n",
    "    while row >= 1:\n",
    "        col = row\n",
    "        n = 0\n",
    "        while n < 9 - row:\n",
    "            print(' ' * 9, end='')\n",
    "            n += 1\n",
    "        while col >=1:\n",
    "            print('{}*{}={:<5d}'.format(row, col, row * col),end='')\n",
    "            col -= 1\n",
    "        print('')\n",
    "        row -= 1\n",
    "\n",
    "multiplication_table()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "***"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 作业3\n",
    "补全代码：\n",
    "1. 实现图片转字符画类I2Char中genCharImage方法pass占位的代码，该方法将图片转化成字符画\n",
    "2. 在main函数中 ，实现通过命令行调用图片转字符画功能pass占位的代码 ,命令行执行 Python v2char.py t3.jpeg,输出字符画"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  理解的不是很好"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "'''\n",
    "@Descripttion: \n",
    "@version: \n",
    "@Author: dkolli\n",
    "@Date: 2019-11-02 09:51:37\n",
    "@LastEditors: sueRimn\n",
    "@LastEditTime: 2019-11-02 12:35:29\n",
    "'''\n",
    "import sys\n",
    "import os\n",
    "import time\n",
    "import threading\n",
    "# import termios\n",
    "# import tty\n",
    "import cv2\n",
    "import pyprind\n",
    "\n",
    "# 基类\n",
    "class CharFrame:\n",
    "\n",
    "    ascii_char = \"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\\\"^`'. \"\n",
    "\n",
    "    # 像素映射到字符\n",
    "    def pixelToChar(self, luminance):\n",
    "        return self.ascii_char[int(luminance/256*len(self.ascii_char))]\n",
    "\n",
    "    # 将普通帧转为 ASCII 字符帧\n",
    "    # limitSize 参数接受一个元组，表示图片的限宽限高。\n",
    "    # fill 表示是否用空格填充图片宽度至限宽，wrap 表示是否在行末添加换行符\n",
    "    def convert(self, img, limitSize=-1, fill=False, wrap=False):\n",
    "        if limitSize != -1 and (img.shape[0] > limitSize[1] or img.shape[1] > limitSize[0]):\n",
    "            img = cv2.resize(img, limitSize, interpolation=cv2.INTER_AREA)\n",
    "        ascii_frame = ''\n",
    "        blank = ''\n",
    "        if fill:\n",
    "            blank += ' '*(limitSize[0]-img.shape[1])\n",
    "        if wrap:\n",
    "            blank += '\\n'\n",
    "        for i in range(img.shape[0]): # shape 为元组 图片的（宽，高）\n",
    "            for j in range(img.shape[1]):\n",
    "                ascii_frame += self.pixelToChar(img[i,j])\n",
    "            ascii_frame += blank\n",
    "        return ascii_frame\n",
    "\n",
    "\n",
    "'''\n",
    "    图片转字符画\n",
    "\n",
    "'''\n",
    "#\n",
    "class I2Char(CharFrame):\n",
    "\n",
    "    result = None\n",
    "\n",
    "    def __init__(self, path, limitSize=-1, fill=False, wrap=False):\n",
    "        self.genCharImage(path, limitSize, fill, wrap)\n",
    "\n",
    "    def genCharImage(self, path, limitSize=-1, fill=False, wrap=False):\n",
    "\n",
    "        # 给self.result 字符画字符串赋值\n",
    "        self.result=''\n",
    "        # img = cv2.imread(path)\n",
    "        # img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
    "        # self.result = self.convert(img1, limitSize, fill, wrap)\n",
    "        # 做了两种尝试，但好像都不是\n",
    "        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n",
    "        self.result = self.convert(img, limitSize, fill, wrap)\n",
    "\n",
    "    def show(self, stream = 2):\n",
    "        if self.result is None:\n",
    "            return\n",
    "        if stream == 1 and os.isatty(sys.stdout.fileno()):\n",
    "            self.streamOut = sys.stdout.write\n",
    "            self.streamFlush = sys.stdout.flush\n",
    "        elif stream == 2 and os.isatty(sys.stderr.fileno()):\n",
    "            self.streamOut = sys.stderr.write\n",
    "            self.streamFlush = sys.stderr.flush\n",
    "        elif hasattr(stream, 'write'):\n",
    "            self.streamOut = stream.write\n",
    "            self.streamFlush = stream.flush\n",
    "        self.streamOut(self.result)\n",
    "        self.streamFlush()\n",
    "        self.streamOut('\\n')\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    import argparse\n",
    "    # 设置命令行参数\n",
    "    parser = argparse.ArgumentParser()\n",
    "    parser.add_argument('file')\n",
    "\n",
    "    args = parser.parse_args()\n",
    "    i2char=I2Char(args.file)\n",
    "\n",
    "    i2char.show()\n",
    "    '''\n",
    "        通过命令行调用图片转字符画功能 ,命令行执行 Python v2char.py t3.jpeg,输出字符画\n",
    "    '''\n",
    "    "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
